import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'package:azlistview/azlistview.dart';

Effect<PlanListViewState> buildEffect() {
  return combineEffects(<Object, Effect<PlanListViewState>>{
    PlanListViewAction.onSubmit: _onSubmit,
    PlanListViewAction.onLoad: _onLoad,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<PlanListViewState> ctx) async {
  await _sendRequest(ctx);
}

void _onLoad(Action action, Context<PlanListViewState> ctx) async {
  await _sendRequest(ctx);
}

_sendRequest(Context<PlanListViewState> ctx) async {
  ResultData res = await CommonNetWork.staffCheckPlans();
  if (res.success) {
    List data = res.data['data'];
    ctx.state.plans =
        data.map<PlanItemModel>((e) => PlanItemModel.fromJson(e)).toList();
    SuspensionUtil.sortListBySuspensionTag(ctx.state.plans);
    SuspensionUtil.setShowSuspensionStatus(  ctx.state.plans);

    ctx.state.refreshController.finishRefresh();
    ctx.dispatch(PlanListViewActionCreator.onAction());
  } else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
    return;
  }
}

void _onSubmit(Action action, Context<PlanListViewState> ctx) {
  UserInfoEntity userInfo = GlobalStore.store.getState().userInfo;
  userInfo.currentPlan = ctx.state.currentIndex;
  userInfo.plans = ctx.state.plans;
  userInfo.isGsUser = false;
  GlobalStore.store.dispatch(GlobalActionCreator.onUserLogin(userInfo));
  bus.emit('refreshMain');
  Navigator.pop(ctx.context);
}
